﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Threading;

namespace NWBA_Public
{
    public partial class BillPay : System.Web.UI.Page
    {
        private static int id;
        private static List<Account> myAcct;
        protected void Page_Load(object sender, EventArgs e)
        {
            //see weather the user has logged in or not
            if ((string)(Session["userName"]) == null)
            {
                //if not logged in direct him to login.aspx
                Response.Redirect("Login.aspx", true);
            }
            Customer cust = Session["Customer"] as Customer;
            //retrieve all the account that associate with this user
            myAcct = AccountRepostiory.Select(cust);
            //associate all the accounts to the dropdownlist for user to select it.
            if (DropDownList2.Items.Count <= myAcct.Count)
            {
                foreach (Account acct in myAcct)
                {
                    DropDownList2.Items.Add(acct.AccountNumber.ToString());
                }
            }
            // Retrieve the bill ID if available in url
            if (!IsPostBack)
            {
                if (Request.QueryString["id"] == null)
                {
                    id = -1;
                }
                else
                {
                    id = Int32.Parse(Request.QueryString["id"]);
                    var bill = BillRepository.SelectSingleBill(id);
                    DropDownList2.SelectedValue = bill.AccountNumber.ToString();
                    ddlToPayee.SelectedValue = PayeeRepository.SelectNameByID(bill.PayeeID);
                    AmountTB.Text = bill.Amount.ToString();
                    cldScheduledDate.SelectedDate = bill.ScheduleDate;
                    ddlPeriod.SelectedValue = toPeriodText(bill.Period);
                }
            }
        }
        // TO check how many accounts that user selected.
        protected Account selectAccount()
        {
            var acctID = from id in myAcct
                         where id.AccountNumber.Equals(int.Parse(DropDownList2.SelectedItem.Value))
                         select id;
            if (acctID.Count() > 1)
            {
                return null;
            }
            foreach (Account acct in acctID)
            {
                return acct;
            }
            return null;
        }

        private char toPeriodChar(string periodText)
        {
            switch (periodText)
            {
                case "One Time":
                    return 'O';
                case "Daily":
                    return 'D';
                case "Monthly":
                    return 'M';
                case "Annual":
                    return 'A';
                default:
                    return ' ';
            }
        }
        private string toPeriodText(char periodChar)
        {
            switch (periodChar)
            {
                case 'O':
                    return "One Time";
                case 'D':
                    return "Daily";
                case 'M':
                    return "Monthly";
                case 'A':
                    return "Annual";
                default:
                    return "";
            }
        }
        protected void ExcuteB_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Account acct = selectAccount();
                int toPayeeID = PayeeRepository.SelectIDByName(ddlToPayee.SelectedValue);
                if (acct != null)
                {
                    Bill newBill = new Bill(acct.AccountNumber, toPayeeID,
                        decimal.Parse(AmountTB.Text), cldScheduledDate.SelectedDate,
                        toPeriodChar(ddlPeriod.SelectedValue));
                    if (((-1 == id && BillRepository.Insert(newBill)) ||
                        (-1 != id && BillRepository.Update(id, newBill))) &&
                        BillRepository.ServiceFee(acct))
                    {
                        Response.Redirect("TransactionStatue.aspx", true);
                    }
                    else
                    {
                        Label Indicator = new Label();
                        Indicator.Text = "Failed to create bill.";
                        PlaceHolder1.Controls.Add(Indicator);
                    }
                }
            }
        }

        protected void AcctValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (DropDownList2.SelectedValue == "Select Account")
            {
                args.IsValid = false;
            }
        }

        public static void Billing(object @lblMsg)
        {
            while (true)
            {
                Thread.Sleep(TimeSpan.FromSeconds(5.0));
                List<Account> allAccounts = AccountRepostiory.SelectAll();
                ((Label)@lblMsg).Text = "";
                foreach (Account acct in allAccounts)
                {
                    ((Label)@lblMsg).Text += BillRepository.TriggerBills(acct, DateTime.MaxValue);
                }
            }
        }
        protected void CancellB_Click(object sender, EventArgs e)
        {
            // Billing async task
            Thread billingThread = new Thread(BillPay.Billing);
            billingThread.Start(@lblErrMsg);

            /*lblErrMsg.Text = "";
            NWBA_Public.Threading.BillingTask billingTask =
                new NWBA_Public.Threading.BillingTask(lblErrMsg);
            PageAsyncTask asyncTask = new PageAsyncTask(billingTask.OnBegin,
                billingTask.OnEnd, billingTask.OnTimeout, "BillingTask", true);
            Page.RegisterAsyncTask(asyncTask);
            Page.ExecuteRegisteredAsyncTasks();*/
            //reset the amount to null
            AmountTB.Text = "";
        }
    }
}